package com.example.service.impl;

import com.example.common.ErrorCode;
import com.example.exception.BusinessException;
import com.example.mapper.OrderMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.UserMapper;
import com.example.model.PageBean;
import com.example.model.order.Order;
import com.example.model.order.OrderAddRequest;
import com.example.model.order.OrderAllInfo;
import com.example.model.user.User;
import com.example.service.OrderService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private UserMapper userMapper;

    public static String get16UUID(){
        // 1.开头两位，标识业务代码或机器代码（可变参数）
        String machineId = String.valueOf(11);
        // 2.中间四位整数，标识日期
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        String dayTime = sdf.format(new Date());
        // 3.生成uuid的hashCode值
        int hashCode = UUID.randomUUID().toString().hashCode();
        // 4.可能为负数
        if(hashCode < 0){
            hashCode = -hashCode;
        }
        // 5.算法处理: 0-代表前面补充0; 10-代表长度为10; d-代表参数为正数型
        String value = machineId + dayTime + String.format("%010d", hashCode);
        return value;
    }

    @Transactional
    @Override
    public Long addOrder(OrderAddRequest orderAddRequest) {
        // 参数验证
        Validate.notNull(orderAddRequest.getRoomId(), "房间ID不能为空");
        Validate.notNull(orderAddRequest.getIsPay(), "支付状态不能为空");
        Validate.notNull(orderAddRequest.getCheckInDate(), "入住日期不能为空");
        Validate.notNull(orderAddRequest.getCheckOutDate(), "退房日期不能为空");

        //订单已支付，修改房间状态
        Long roomId=orderAddRequest.getRoomId();
        Integer isPay=orderAddRequest.getIsPay();
        //房间是否可用
        Integer roomStatus= roomMapper.getRoomStatus(roomId);
        Order order = getOrder(orderAddRequest, roomStatus);

        //TODO
        //校验房间id和酒店id是否匹配

        Date checkInDate=orderAddRequest.getCheckInDate();
        Date checkOutDate=orderAddRequest.getCheckOutDate();

        //入住时间是否小于退房时间
        if (!checkInDate.before(checkOutDate)) {
            throw new BusinessException(ErrorCode.ORDER_DATE_ERROR);
        }

        //生成订单
        orderMapper.add(order);
        if (isPay==0){
            return order.getId();
        }
        //2.修改房间状态
        Boolean result=roomMapper.setRoomStatus(roomId,isPay);
        if (!result)
            throw new BusinessException(ErrorCode.ROOM_STATUS_ERROR,"房间状态设置失败");
        return order.getId();
    }



    @Override
    public OrderAllInfo getOrderById(Long id) {
        return orderMapper.getById(id);
    }

    @Override
    public List<OrderAllInfo> getByUserId(Long userId) {
        return orderMapper.getByUserId(userId);
    }

    @Override
    public PageBean getAllOrder(Integer pageSize,Integer pageNum,String orderNumber,Long hotelId,String username) {
        //设置分页参数
        PageHelper.startPage(pageNum,pageSize);

        //执行查询结果
        List<OrderAllInfo> allOrder = orderMapper.getAllOrder(orderNumber,hotelId,username);
        Page<OrderAllInfo> p= (Page<OrderAllInfo>) allOrder;

        //封装返回对象
        PageBean pageBean=new PageBean(p.getTotal(),p.getResult());
        return pageBean;
    }

    @Override
    public List<OrderAllInfo> getByHotelId(Long hotelId) {
        return orderMapper.getByHotelId(hotelId);
    }

    @Override
    public Integer getOrderStatus(Long id) {
        return orderMapper.getOrderStatus(id);
    }

    @Transactional
    @Override
    public Boolean updateOrderStatus(Long id, Integer status, Long roomId) {
        //获取订单状态
        Integer orderStatus=orderMapper.getOrderStatus(id);
        if(orderStatus.equals(status)){
            throw new BusinessException(ErrorCode.ORDER_ERROR,"订单已经是此状态");
        }
        //修改订单状态
        Boolean result=orderMapper.setOrderStatus(id,status);

        //设置房间状态
        //入住，修改房间已入住
        if (status==3)
            roomMapper.setRoomStatus(roomId,2);
        //取消/订单已完成，修改房间空闲
        if (status==2||status==4)
            roomMapper.setRoomStatus(roomId,0);
        //支付，修改房间已预定
        if (status==1)
            roomMapper.setRoomStatus(roomId,1);
        return result;
    }

    //idea优化，提取方法
    private static Order getOrder(OrderAddRequest orderAddRequest, Integer roomStatus) {
        if(roomStatus !=0){
            throw new BusinessException(ErrorCode.ROOM_STATUS_ERROR,"房间不可预订");
        }
        //生成订单号 uuid
        String orderNumber=get16UUID();

        Order order=new Order();
        order.setOrderNumber(orderNumber);
        order.setOrderStatus(orderAddRequest.getIsPay());
        order.setHotelId(orderAddRequest.getHotelId());
        order.setRoomId(orderAddRequest.getRoomId());
        order.setUserId(orderAddRequest.getUserId());
        order.setCheckInDate(orderAddRequest.getCheckInDate());
        order.setCheckOutDate(orderAddRequest.getCheckOutDate());
        return order;
    }
}
